﻿using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using xmgl.Models;

namespace xmgl.Dal
{
    public class UserDal : BaseDal<User>
    {
        public override void Add(User bean)
        {
            dbOp.Users.Add(bean);
            dbOp.SaveChanges();
        }

        public override void Del(User bean)
        {
            dbOp.Users.Remove(bean);
            dbOp.SaveChanges();
        }

        public override void Modify(User bean)
        {
            DbEntityEntry<User> entry = dbOp.Entry<User>(bean);
            entry.State = System.Data.Entity.EntityState.Unchanged;

            if (!string.IsNullOrEmpty(bean.Name))
            {
                entry.Property("Name").IsModified = true;
            }
            if (!string.IsNullOrEmpty(bean.Note))
            {
                entry.Property("Note").IsModified = true;
            }
            dbOp.SaveChanges();
        }

        public override List<User> Query(User bean)
        {
            var ds = dbOp.Users;

            if (bean.Id != 0)
            {
                ds.Where<User>(d => d.Id == bean.Id);
            }
            if (!string.IsNullOrEmpty(bean.Name))
            {
                ds.Where<User>(d => d.Name.Contains(bean.Name));
            }
            if (!string.IsNullOrEmpty(bean.Note))
            {
                ds.Where<User>(d => d.Note.Contains(bean.Note));
            }
            return ds.ToList();
        }

        public override List<User> QueryByPage(User bean, int page, int rows, ref int count)
        {
            var ds = dbOp.Users;

            if (bean.Id != 0)
            {
                ds.Where<User>(d => d.Id == bean.Id);
            }
            if (!string.IsNullOrEmpty(bean.Name))
            {
                ds.Where<User>(d => d.Name.Contains(bean.Name));
            }
            if (!string.IsNullOrEmpty(bean.Note))
            {
                ds.Where<User>(d => d.Note.Contains(bean.Note));
            }
            count = ds.Count();
            return ds.Skip((page - 1) * rows).Take(rows).ToList();
        }
    }
}